package com.yjs.app.trade.core.util;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DESUtils {

	private static final String DES = "DES";

	private static Logger logger = LoggerFactory.getLogger(DESUtils.class);

	/**
	 * 加密
	 * 
	 * @param data
	 * @param sKey
	 * @return
	 */
	public static byte[] encrypt(String str, String sKey) {
		byte[] data = null;
		try {
			data = str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		byte[] key = sKey.getBytes();
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 从原始密匙数据创建DESKeySpec对象
			DESKeySpec desKey = new DESKeySpec(key);
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成securekey
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance(DES);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
			// 正式执行加密操作
			return cipher.doFinal(data);

		} catch (Exception e) {
			logger.error("DES加密失败：" + e);
		}

		return null;
	}
	
	/**
	 * 加密并返回加密后字符串
	 * @return
	 */
	public static String getEncryptStr (String str, String sKey) {
		return byte2String(DESUtils.encrypt(str, sKey));
	}

	/**
	 * 解密
	 * 
	 * @param src
	 * @param sKey
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, String sKey) {
		byte[] key = sKey.getBytes();

		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 创建一个DESKeySpec对象
			DESKeySpec desKey = new DESKeySpec(key);
			// 创建一个密匙工厂
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance(DES);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
			// 真正开始解密操作
			return cipher.doFinal(src);

		} catch (Exception e) {
			logger.error("DES解密失败：" + e);
		}

		return null;
	}

	/**
	 * 解码并返回解码后的字符串
	 * @return
	 */
	public static String getDecryptStr (String str, String sKey) {
		try {
			return new String(DESUtils.decrypt(string2byte(str) , sKey), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 二进制 转 字符串
	 * 
	 * @param b
	 * @return
	 * @author: Tandong
	 * @date: 2018年2月9日 下午2:07:14
	 */
	public static String byte2String(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs;
	}

	/**
	 * 字符串 转 二进制
	 * 
	 * @param b
	 * @return
	 * @author: Tandong
	 * @date: 2018年2月9日 下午2:37:49
	 */
	public static byte[] string2byte(String str) {
		byte[] b = null;
		try {
			b = str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	public static void main(String[] args) {
		try {
			String str = "Bmmdit9#";
			String enStr = byte2String(DESUtils.encrypt(str, "yjs_trade_app"));
			System.out.println("加密：" + enStr);
			System.out.println("解密：" + new String(DESUtils.decrypt(string2byte(enStr) , "yjs_trade_app")));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
